//
//  PKRequestManager.m
//  PianKe
//
//  Created by apple on 15/9/26.
//  Copyright (c) 2015年 lanou3g.com蓝鸥科技有限公司. All rights reserved.
//

#import "PKRequestManager.h"

@implementation PKRequestManager

- (void)requsetWithType:(RequestType)type URLString:(NSString *)urlString ParDIc:(NSDictionary *)parDic finish:(RequsetFinish)finish error:(RequserError)error
{// 拿到参数后进行请求
    NSURL *url = [NSURL URLWithString:urlString];
    // 创建可变的URLRequset
  NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url];
    // 如果请求方式是POST需要设置参数和请求方式
    if (type == POST) {
        // 设置请求方式
        [requset setHTTPMethod:@"POST"];
        // 设置请求参数的body体
        if (parDic.count > 0) {
            NSData *data = [self parDicToDataWithDic:parDic ];
            [requset setHTTPBody:data];
        }
        
    }

    [NSURLConnection sendAsynchronousRequest:requset queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            finish(data);
        }else
        {
            error(connectionError);
        }        
    }];



}
// 把参数字典转化成POST请求所需要的参数体
- (NSData *)parDicToDataWithDic:(NSDictionary *)dic
{
    NSMutableArray *array = [NSMutableArray array];
    // 遍历字典得到每一个键 ，得到所有的Key=value类型的字符串
    for (NSString *key in dic) {
        NSString *str = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        [array addObject:str];
    }
    // 数组中所有的元素通过&来连接
    NSString *parString = [array componentsJoinedByString:@"&"];

    return [parString dataUsingEncoding:NSUTF8StringEncoding];
}

+ (void)PKRequestManagerrequsetWithType:(RequestType)type URLString:(NSString *)urlString ParDIc:(NSDictionary *)parDic finish:(RequsetFinish)finish error:(RequserError)error
{

  PKRequestManager *manager =  [[PKRequestManager alloc]init];
    [manager requsetWithType:type URLString:urlString ParDIc:parDic finish:finish error:error];
    
}

@end
